package engine.newUi
{
	import com.greensock.TweenLite;
	import com.greensock.plugins.BlurFilterPlugin;
	import com.greensock.plugins.TweenPlugin;
	
	import engine.control.MiniLoadingBar;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.Record;
	import engine.data.ResPath;
	import engine.data.RoleVo;
	import engine.event.SoundEvent;
	import engine.logic.LogSendLogic;
	import engine.logic.McPool;
	import engine.logic.RequestForCost;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.tip.TipsMainLogic;
	import engine.tip.tipItem.BookKungfuItem;
	import engine.tip.tipItem.KungfuItem;
	import engine.ui.MsgTipsLogic;
	import engine.util.FilterUtil;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.system.Capabilities;
	
	import newx.StageInfo;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.button.NxButton;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;
	import newx.com.loader.SwfLoader;
	import newx.utils.BitmapAPI;
	import newx.utils.MemoryOptimise;
	
	
	/**
	 *色子 
	 * @author yanghr
	 * 
	 */
	public class DiceLogic
	{
		private static var _self:DiceLogic;
		public static function getInstance():DiceLogic
		{
			if(_self==null)
			{
				_self=new DiceLogic();
			}
			return _self;
		}
		public function get ui():DiceUI
		{
			if(_ui==null)
			{
				_ui=new DiceUI;
			}
			return _ui
		}
		private const NORMAL_FRAM:int=1,ONLY_SALE_FRAM:int=2;
		private const NPC_NORMAL:int=4,NPC_DISBLE:int=1,NPC_NOR_ROLL:int=3;
		private const WIN:int=1,TIE:int=2, LOSE:int=3;
		private var _bind:BindManage;
		private var _model:ModelLocator
		private var _role:RoleVo;
		private var _tip:TipsMainLogic;
		private var _ui:DiceUI;
		private var _blagVipFlag:int=-1;
		private var _blagLvlFlag:int=-1;
		private var _blagfreeFlag:int=-1;
		private var _blagMoneyFlag:int=-1;
		private var _blagGoldFlag:int=-1;
//		private var _blagFakeFlag:int=-1;
		private var _constipateArr:Array;
		private var _maxNpcIndex:int;
		private var _lastLen:int;
		private var _waitIngflag:Boolean=false
			
		private var _mx:Matrix=new Matrix
		/**
		 *在一键什么种 
		 */		
		private var _beginOneClick:Boolean
		/**
		 *能否重金收买 
		 */		
		private var _canGoldBuy:Boolean=false;
		
		private var isIndex4:Boolean	=	false;
		
		private var _isAzoth:Boolean=false;

		private const GRAY:ColorMatrixFilter=FilterUtil.GrayColorFilter;
		private const BG:String="bg";
		private const BG2:String="Bg22";
		private const IMG:String="img01";
		private const	PRAC_BTN:String="bt_1",SALE_BTN:String="bt_2";
		private const NAME:String="titleTxt2";
		private const INFO:String="infoTxt4";
		private const NPC:String="npcMc",ARROW:String="arror_";
		private const INDEX:String="index";
		private const BOOK:String="BookType";
		
		private const PHOTO:String="EffectivePhoto"
		
		private const DATA:String="data";
		private const CONFIGID:String="ConfigID";
		private const MODEL:String="Photo";
		
		private const PRACTICE:String="practice";
		private const SALE:String="sale";
		private const SPLIDER:String="&%&";
		
		private const MAX_COUNT:int=20;
		
		private const CURR_SALE:int=1,CURR_PRAC:int=2,CURR_NONE:int=3,CURR_BUY:int=4;
		/**
		 * 
		 */		
		private var _firDiceCountArr:Array;
		/**
		 * 
		 */		
		private var _secDiceCountArr:Array;
		private var _bookTips:BookKungfuItem;
		private var _rollMc:MovieClip;
		private var _currentNpc:MovieClip;
		private var _npcConfigTips:Array;
		/**
		 *动画相关 
		 * _currentAnimalFlag 操作队列
		 */		
		private var _currentAnimalFlag:int, _currentObj:Object={},_arrAnimalstuck:Array=[];
		
		private var _result:NxLabel=new NxLabel;
		private var _initGold:int;
		private var _initSale:int;
		private var _totalFreeCount:int;
		private var _lvl:int=0
		private var _vip:int=0;
		
		
		private var sprite:Shape=new Shape();
		private var btn:NxButton=new NxButton();
		
		private const DICE_TYPE:int = 2;
		private var _recordArr:Array;
		private var exchangeMoneyCount:int;
		private var canGoldBug:Boolean	=	false;
		public function set canGoldBuy(value:Boolean):void 
		{
			_canGoldBuy=value;
			if(!canGoldBug) return;
			if(!_canGoldBuy)
			{
				_ui.Btn.goldBtn.enabled	=	false;
				_ui.Btn.goldBtn.filters=[FilterUtil.GrayColorFilter];
			}
			else
			{
				_ui.Btn.goldBtn.enabled	=	true;
				_ui.Btn.goldBtn.filters=null
			}
		}
		/**
		 *是否是用的水银骰子 //没这个功能了
		 */
		public function set isAzoth(value:Boolean):void
		{
			if(value)
			{
				_ui.bk3.gotoAndStop(2)
				_ui.bk2.gotoAndStop(1)
			}
			else
			{
				_ui.bk3.gotoAndStop(1)
				_ui.bk2.gotoAndStop(2)
			}
			_isAzoth = value;
		}
		public function get isAzoth():Boolean
		{
			return _isAzoth;
		}
		public function  Init():void
		{
			TweenPlugin.activate([BlurFilterPlugin]);
			_bind=BindManage.getInstance();
			_model=ModelLocator.getInstance();
			_role=_model.scene.Role;
			_tip=TipsMainLogic.instance;
			_bookTips=new BookKungfuItem;
//			ui.exchangeBtn.label=StaticIni.getSwfLangStr("Kungfu_UIString4");
//			ui.bankBtn.label=StaticIni.getSwfLangStr("ActivityStr_2");
			sprite.graphics.beginFill(0x000000,1);
			sprite.graphics.drawRect(-Capabilities.screenResolutionX/2,-Capabilities.screenResolutionY/2,
				Capabilities.screenResolutionX*2,Capabilities.screenResolutionY*2);
			sprite.graphics.endFill();
//			MainUIManager.getInstance().downPlace.addChild(sprite);
			_ui.addChildAt(sprite,0)
			mask=false
//			_ui.Btn.diceBtn.label="一键扔色子";
//			_ui.Btn.sellBtn.label="一键出售";
//			_ui.Btn.practiceBtn.label="一键练习";
//			_ui.Btn.packBtn.label="包裹";
//			_ui.Btn.exitBtn.label="离开";
//			_ui.normalLab.htmlStr="普通骰子";
//			_ui.azothLab.htmlStr="水银骰子";
			MemoryOptimise.stopMovie(_ui.pp);
			_ui.windowBG.addChild(_result);
			_ui.seletedMc.gotoAndStop(1);
			_result.x=200;
			_result.y=50;
//			ActivitesGroupLogic.getInstance().registShowOrHideCallBack(2,function():void{ui.bankBtn.visible=true;},function():void{ui.bankBtn.visible=false});
//			isAzoth=false;
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_KUNGFU_SCHEDULE),process)
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_KUNGFU_RECORD),info)
		}
		private function initBK():void
		{
			MiniLoadingBar.getInstance().show(StaticIni.getSwfLangStr("UIString_1000628"));
			SwfLoader.StartLoad(
				StageInfo.swfResPath + "diceBG.swf",
				null,
				onLoadSuccess,[onLoading]);
			ui.visible=false;
		}
		private function onLoadSuccess(val:DisplayObject, pList:Array = null):void
		{
			var nx:NxClip=_ui.bk5 as NxClip;
			nx.source=val;
			ui.visible=true;
			
			if(!_ui.Btn)
			{
				_ui.Btn=val["bk6"];
			}
			if(!_ui.pp)
			{
				_ui.pp=val["pp"];
			}
			_initGold=_ui.Btn.goldBtn.x;
			_initSale=_ui.Btn.diceBtn.x;
			_endStat=(ui.Btn.exitBtn as SimpleButton).upState;
			_end2Stat=(ui.Btn.exitBtn as SimpleButton).overState;
			//_ui.pp.mouseEnabled=val["bkbk"].mouseChildren=val["bkbk"].mouseEnabled=false;
			/*(val as Sprite).mouseEnabled=*/(val as Sprite).mouseChildren=true
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_GET_KUNGFU_UI);
			addAllEventListener()
		}
		private function onLoading(e:Event):void
		{
			var pe:ProgressEvent=e as ProgressEvent;
			if(pe)
			MiniLoadingBar.getInstance().progress=pe.bytesLoaded/pe.bytesTotal;
		}
		private function process(e:CustomMsgEvent):void
		{
//			trace("DiceLogic.process(e)进度",e.pList,e.pList.length);
			var maxIndex:int=0;
			for (var i:int = 0; i < e.pList.length; i+=2) 
			{
				var b:Boolean=Boolean(e.pList[i+1]);
				if(b)
				{
					maxIndex=Math.max(e.pList[i],maxIndex);
				}
				if(e.pList[i]==0)
					continue;
				setNpc((e.pList[i]),b);
			}
			maxNpcIndex=maxIndex;
		}
		public function set maxNpcIndex(value:int):void 
		{
			_maxNpcIndex=value;
			_ui.arrowMain.x=ui.pp.x+ui.pp[NPC+value].x+(ui.pp[NPC+value].width-	_ui.arrowMain.width)/2+ui.pp.parent.x+ui.pp.parent.parent.x
		}
		private function getCompareArr(arr1:Array,arr2:Array):Array
		{
			if(arr1==null||arr2==null)
			{
				return null;
			}
			var arr:Array=[];
			var arr3:Array=arr1.concat();
			var arr4:Array=arr2.concat();
			var index:int=-1;
			for (var i:int = 0; i < arr3.length; i++) 
			{
				var configid:int=arr3[i];
				var tempindex:int	=	(_currentObj&&_currentObj.hasOwnProperty(configid))?_currentObj[configid]:-1;
				index=arr4.indexOf(configid);
				if(index	==	-1	&&	(tempindex==-1||tempindex==i))
				{
					arr.push(i);
				}
				else
				{
					if(index	!=	-1	)
					{
						arr4.splice(index,1);
					}
					else if(tempindex!=-1)
					{
						arr.push(tempindex);
					}
				}
			}
			return arr;
			
		}
		private function tweenAll(indexArr:Array):void
		{
			for each (var i:int in indexArr) 
			{
				var b:Boolean	=	tweenSingle(i);
				if(!b)break;
			}
			
		}
		private function tweenSingle(index:int):Boolean
		{
			var mc:MovieClip=_ui.constipatGroup.getItemByIndex(index);
			mc.visible=false;
			if(mc[DATA])
			{
				var bitmap:DisplayObject=KungfuPackLogic.getInstance().getBitMapInSamePoint(mc);//McPool.borrowRes(mc[DATA][PHOTO])//mc[BG2].content;
			}
			if(mc[DATA]==null||bitmap==null)
			{
				reset();
				return false;
			}
//			var bitmap:Bitmap=KungfuPackLogic.getInstance().getBitMapInSamePoint;
			var target:DisplayObject=_ui.Btn.packBtn;
			var point:Point=target.parent.localToGlobal(new Point(target.x,target.y))
//			TweenLite.to(bitmap,0.3,{blurFilter:{blurX:5,blurY:5},onComplete:move});
				move();
				return true;
			function move():void
			{
				TweenLite.to(bitmap,1,{x:point.x	,	y:point.y	,scaleX:0.1,scaleY:0.1,onComplete:disappear})
			}
			function disappear():void
			{
				bitmap.parent.removeChild(bitmap);
				reset();
			}
			function reset():void
			{
				if(_waitIngflag)
				{
					reSetInfo();
				}
//				mc.visible=true;
			}
		}
		private function info(e:CustomMsgEvent):void
		{
//			trace("DiceLogic.info(e)信息",e.pList,e.pList.length);
			_currentAnimalFlag=_arrAnimalstuck.shift();
//			trace("DiceLogic.info(e)","SALE:",_currentAnimalFlag==CURR_SALE,"prac:",_currentAnimalFlag==CURR_PRAC,_arrAnimalstuck.length);
			if(_constipateArr&&Math.abs(e.pList.length-_constipateArr.length)>1&&_arrAnimalstuck.length>0&&_currentAnimalFlag==CURR_BUY)
			{
				_currentAnimalFlag=function f():int{var a:int=_arrAnimalstuck.shift();if(a==CURR_BUY)return f();return a}();
			}
			canGoldBuy=e.pList.length!=MAX_COUNT&&!isIndex4;
//			if(_currentAnimalFlag==0||_currentAnimalFlag==CURR_BUY)
//			{
//				_constipateArr=e.pList;
//				reSetInfo();
//				return ;
//			}
			_waitIngflag=true;
			var ar:Array=	getCompareArr(_constipateArr,e.pList);;
			if(_constipateArr&&e.pList.length<_constipateArr.length	&&_currentAnimalFlag==CURR_PRAC	&&ar	&&ar.length)
			{
				_constipateArr=e.pList;
				tweenAll(ar);
			}
			else
			{
				ar	=	getCompareArr(e.pList,_constipateArr);
				if(ar&&ar.length)
				{
					_constipateArr=e.pList;
					getAddKungfu(ar)
				}
				else
				{
					ar=getCompareArr(_constipateArr,e.pList);
					getRemoveKungfu(ar);
					_constipateArr=e.pList;
				}
				reSetInfo()
			}
		}
		private function getRemoveKungfu(arr:Array):void
		{
			for each (var i:int in arr) 
			{
				var configid:String=_constipateArr[i];
//				if(StaticIni.getIniObj(configid)["KungFuPrize"]==6000)
//					trace("0000000000000000000000000000000000000000000000000000000000000000000")
//				trace("DiceLogic.getRemoveKungfu(arr)","价格",StaticIni.getIniObj(configid)["KungFuPrize"],_currentAnimalFlag==CURR_SALE);
//				trace("当前出售的物品id："+configid,"名字："+StaticIni.getSwfLangStr(configid+"")	/*,"   品质:"+StaticIni.getIniVar(configid+"","KungFuQuality")*/,"位置"+i,"价格",StaticIni.getIniObj(configid)["KungFuPrize"]);
				var container:DisplayObjectContainer=MsgTipsLogic.getTempContainer(_ui.constipatGroup.getItemByIndex(i));
				var info:String=StaticIni.getSwfLangStrVar("30010",[StaticIni.getIniObj(configid)["KungFuPrize"]]);
				MsgTipsLogic.getRes(container).showInfo(info);
			}
		}
		private function getAddKungfu(arr:Array):void
		{
			for each (var i:int in arr) 
			{
				var configid:String=_constipateArr[i];
				_bookTips.data=_tip.getStaticObjWithID(configid)
//				trace("当前增加的物品id："+configid,"名字："+StaticIni.getSwfLangStr(configid+"")	,"   品质:"+StaticIni.getIniVar(configid+"","KungFuQuality"))
				MsgTipsLogic.getRes(_currentNpc).showInfo(StaticIni.getSwfLangStrVar("Kungfu_UIString25",[_bookTips.getColorName()]))
			}
			
			
		}
		private function reSetBtn():void
		{
			var practb:SimpleButton=(_ui.Btn["practiceBtn"] as SimpleButton);
			var sellB:SimpleButton=_ui.Btn["sellBtn"] as SimpleButton
			var diceB:SimpleButton=ui.Btn["diceBtn"]	as SimpleButton;
			var pracEnable:Boolean;
			var sellEnable:Boolean;
			var diceEnalbe:Boolean=_constipateArr.length<20 
									&&(_vip>=StaticIni.getIniObj("DiceLogic_Need")["oneClick_vip"]
										|| _lvl>=StaticIni.getIniObj("DiceLogic_Need")["oneClick_Lvl"]);
			sellEnable=!_beginOneClick;
			for (var i:int = 0; i < _constipateArr.length; i++) 
			{
				var obj:Object=StaticIni.getIniObj(_constipateArr[i]);
				if(!obj)continue;
				if(obj["KungFuQuality"]==KungfuItem.GRAY)
				{
//					sellEnable=true;
				}
				else
				{
					pracEnable=true;
				}
				if(pracEnable&&sellEnable)
					break;
			}
			enable(sellB,sellEnable)
			enable(practb,pracEnable)
			enable(diceB,diceEnalbe)
		}
		
		private function enable(btn:SimpleButton,enable:Boolean):void
		{
			if(btn==_ui.Btn.goldBtn && isIndex4) return;
			btn.enabled=enable;
			btn.filters=enable?null:[GRAY];
		}
		
		/**
		 *一键收买后的自动拾取 
		 * 
		 */		
		private function autoPickInOneClick():void
		{
			(_ui.Btn["practiceBtn"] as EventDispatcher).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		}
		/**
		 *刷新全部显示 
		 * 
		 */		
		private function reSetInfo():void
		{
//			if(_currentAnimalFlag==CURR_NONE)
//				return ;
			_currentObj	=	{};
//			trace("DiceLogic.reSetInfo()xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",_currentAnimalFlag);
			_waitIngflag=false;
			var arr:Array=_constipateArr;
			refreshKungfu();
			var b:Boolean=_beginOneClick
			_beginOneClick	=checkOneDice();
			//如果是一键猎命 且 现在要停止
			_currentAnimalFlag=CURR_NONE;
			if(_beginOneClick==false	&&	b	&&_ui.seletedMc.currentFrame==2)
			{
				autoPickInOneClick();
			}
			
			_lastLen=arr.length;
			reSetBtn();
			if(_beginOneClick)
			{
				clickMaxNpc();
			}
			function checkOneDice():Boolean
			{
				if(_beginOneClick)
				{
					if(_lastLen<arr.length&&arr.length<MAX_COUNT	&&	_maxNpcIndex!=5)
					{
						return true;
					}
				}
				return false;
			}
		}
		/**
		 *黑色遮罩 
		 * @param enable
		 * 
		 */		
		public function set mask(enable:Boolean):void
		{
			sprite.visible=enable;
//			sprite.parent.setChildIndex(sprite,sprite.parent.numChildren-1);
		}
		public function	BeforeShow():void
		{
			
			//取到本地
			_recordArr = new Array();
			var _record:Record = _model.scene.GetRecordEx("FakeVipRec");
			var _arr:Array = _record.recArr;
			for(var i:String in _arr){
				if(_arr[i][0] == DICE_TYPE){
					_recordArr.push(_arr[i][0], _arr[i][1]);
				}
			}
			
			mask=true;
			_ui.arrowMain.visible=true;
			_ui.arrowMain["play"]();
			if(!_ui.bk5["source"])
			{
				initBK();
				currentNpc = new MovieClip();
			}
			else
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_GET_KUNGFU_UI);
				addAllEventListener()
			}
			
			
		}
		public function	AfterHide():void
		{
			mask=false;
			_recordArr = [];
			removeAllEventListener()
		}
		private function linkHandle(e:Event):void
		{
			var mc:MovieClip=e.currentTarget as MovieClip;
			var target:DisplayObject=e.target as DisplayObject;
//			var arr:Array=e.text.split(SPLIDER);
//			var str:String=arr[0]
			var index:int=mc[INDEX];
			if(mc[DATA])
			{
				if(mc[PRAC_BTN]==(target))
				{
					practiceOne(mc);
				}
				else if(mc[SALE_BTN]==(target))
				{
//					_currentAnimalFlag=CURR_SALE;
					_arrAnimalstuck.push(CURR_SALE);
					_currentObj[mc[DATA]["ConfigID"]]=index;
					send(index,2);
				}
			}
		}
		/**
		 *发送出售或放进背包的消息 
		 * @param i
		 * @param type
		 * 
		 */		
		private function send(i:int,type:int):void
		{
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_OPERATOR_KUNGFU,type,i)
		}
		private function practiceOne(mc:MovieClip):void
		{
			var index:int=mc[INDEX];
//			_currentAnimalFlag=CURR_PRAC;
			_arrAnimalstuck.push(CURR_PRAC);
			_currentObj[mc[DATA]["ConfigID"]]=index;
			send(index,1)
		}
		/**
		 *心法tips 
		 * @param e
		 * 
		 */		
		private function bookrollOver(e:Event):void
		{
			var mc:MovieClip=e.currentTarget as MovieClip;
			if(!mc[DATA])return
			_bookTips.data=mc[DATA];
			_tip.showByItem(_bookTips);
		}
		private function npcRoll(e:Event):void
		{
			var mc:MovieClip=e.target as MovieClip;
			if(_npcConfigTips==null)
			{
				_npcConfigTips=String(StaticIni.getIniObj("KungFuNpcTips")["Name"]).split(",");
			}
			var mainStr:String=e.target.name;
			if(mainStr.indexOf("npcMc")==-1)return ;
			var str:String=mainStr.charAt(mainStr.length-1);
			if(int(str)>0)
			{
				_tip.showMain(StaticIni.getSwfLangStr(_npcConfigTips[int(str)-1]));
			}
			rollMc=mc;
		}
		private function npcOut(e:Event):void
		{
			rollMc=null;
			_tip.hide()
		}
		public function set rollMc(value:MovieClip):void
		{
			if(_rollMc)
			{
				if(_rollMc.currentFrame==NPC_NOR_ROLL)
				{
					_rollMc.gotoAndStop(NPC_NORMAL);
				}
			}
			_rollMc=value;
			if(_rollMc)
			{
				if(_rollMc.currentFrame==NPC_NORMAL)
				{
					_rollMc.gotoAndStop(NPC_NOR_ROLL)
				}
			}
		}
		private function btnTips(e:Event):void
		{
			var dp:DisplayObject=e.target as DisplayObject;
			var tips:String;
			if( _ui.Btn["diceBtn"]==(dp))
			{
				if(!_ui.Btn["diceBtn"].enabled && _lastLen<MAX_COUNT)
				{
					tips=StaticIni.getSwfLangStr("Kungfu_UIString27");
				}
			}
			else if( _ui.Btn.sellBtn==(dp))
			{
			}
			else if(  _ui.Btn.practiceBtn==(dp))
			{
			}
			else if(  _ui.Btn.packBtn==(dp))
			{
			}
			else if(  _ui.Btn.exitBtn==(dp))
			{
				ui.Btn.exitBtn.overState=_end2Stat;
			}
			else if(_ui.Btn.goldBtn==dp)
			{
				if(_vip==0)
				{
					tips=tips=StaticIni.getSwfLangStr("Kungfu_UIString26")
				}
				else if(_vip<=3 && !_ui.Btn.goldBtn.enabled && !canGoldBug)
				{
					tips=StaticIni.getSwfLangStr("Kungfu_UIString28");
				}
				else
				{
					tips=StaticIni.getSwfLangStr("Kungfu_ExcTips3");
				}
			}
			else if(_ui.bk4.contains(dp))
			{
			}
			else
			{
				trace("DiceLogic.btnTips(e)",e.target);
				
			}
				_tip.showMain(tips);
		}
		private function arrowTips(e:Event):void
		{
			_tip.showMain(StaticIni.getSwfLangStr("Kungfu_UIString11"));
		}
		private function goldrollOver(e:Event):void
		{
			var target:NxLabel=e.currentTarget as NxLabel;
			var tips:String;
			if(target==_ui.moneyLab)
			{
				tips=	 StaticIni.getSwfLangStr("GoldCoin")+":" + _role.getGoldCoin();
			}
			else if(target==_ui.goldLab)
			{
				tips=	 StaticIni.getSwfLangStr("MagicCoin")+":" + _role.getMagicCoin();
			}
			_tip.showMain(tips);
		}
		
		/**
		 * 
		 */			
		public function addAllEventListener():void
		{
			_ui.windowBG.addEventListener(MouseEvent.CLICK,clickHandle);
			_ui.pp.addEventListener(MouseEvent.MOUSE_OVER,npcRoll);
			_ui.pp.addEventListener(MouseEvent.MOUSE_OUT,npcOut);
			_ui.goldLab.addEventListener(MouseEvent.ROLL_OVER,goldrollOver);
			_ui.moneyLab.addEventListener(MouseEvent.ROLL_OVER,goldrollOver);
			_ui.arrowMain.addEventListener(MouseEvent.ROLL_OVER,arrowTips)
			_ui.arrowMain.addEventListener(MouseEvent.ROLL_OUT,_tip.hide)
//			_ui.windowBG.addEventListener(TextEvent.LINK,linkHandle);
			_ui.constipatGroup.addItemsEvent(MouseEvent.ROLL_OVER,bookrollOver);
			_ui.constipatGroup.addItemsEvent(MouseEvent.ROLL_OUT,_tip.hide);
			_ui.Btn.addEventListener(MouseEvent.MOUSE_OVER,btnTips);
			_ui.Btn.addEventListener(MouseEvent.MOUSE_OUT,_tip.hide);
			_ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,close);
			if(_blagVipFlag==-1)
			{
				_blagVipFlag=_bind.BindProp(_role,ActorPropertyUI.VIP_LEVLE,this,"viplevel")
			}
			if(_blagfreeFlag==-1)
			{
				_blagfreeFlag=_bind.BindProp(_role,"PlayerFreeCount",this,"freeCount")
			}
			if(_blagLvlFlag==-1)
			{
				_blagLvlFlag==_bind.BindProp(_role,ActorPropertyUI.LEVEL,this,"level")
			}
			if(_blagGoldFlag==-1)
			{
				_blagGoldFlag=_bind.BindProp(_role,"MagicCoin",this,"gold")
			}
			if(_blagMoneyFlag==-1)
			{
				_blagMoneyFlag=_bind.BindProp(_role,"GoldCoin",this,"money")
			}
			BindManage.getInstance().BindRecord(_model.scene,"VIPCountRec",addData,removeData);
//			bindList.push({propName:"GoldCoin"				,setTypefuncName:"changePlayerGoldCoin"});
//			//元宝
//			bindList.push({propName:"AccountPoints"		,setTypefuncName:"changePlayerAccountPoints"});
		}
		
		private function addData(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			var arr:Array = PropertiesValue;
			var type:int = arr[0];
			var useCount:int = arr[1];
			var allCount:int = arr[2];
			var cardCount:int = arr[3];
			switch (type)
			{
				case 1:
					exchangeMoneyCount = allCount + cardCount - useCount;
					break;
				case 19:
					var MoneyCount:int = allCount + cardCount - useCount;
					canGoldBug = MoneyCount >0 ? true : false;
					enable(_ui.Btn.goldBtn,canGoldBug);
					break;
			}
		}
		
		private function removeData(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			
		}
		
		/**
		 *按钮排序 
		 * 
		 */		
		private function sortBtn():void
		{
			if(_ui.Btn.diceBtn.visible==false)
			{
				if(_ui.Btn.goldBtn.visible==true)
				{
					_ui.Btn.goldBtn.x=_initSale;
				}
			}
			else
			{
				if(_ui.Btn.goldBtn.visible==true)
				{
					_ui.Btn.goldBtn.x=_initGold;
				}
			}
		}
		public function set level(value:int):void
		{
			_lvl=value;
			refreshDiceBtn();
			sortBtn();
		}
		private function refreshDiceBtn():void
		{
			var boolean:Boolean	=	(_lvl>=StaticIni.getIniObj("DiceLogic_Need")["oneClick_Lvl"]||_vip>=StaticIni.getIniObj("DiceLogic_Need")["oneClick_vip"]);
			enable(_ui.Btn.diceBtn,boolean);
			_ui.seletedLab.visible=_ui.seletedMc.visible=(_lvl>=StaticIni.getIniObj("DiceLogic_Need")["selectCompose_lvl"]||_vip>=StaticIni.getIniObj("DiceLogic_Need")["selectCompose_vip"]);
		}
		public function set viplevel(value:int):void
		{
			_vip=value;
			var boolean:Boolean	=	value>=StaticIni.getIniObj("DiceLogic_Need")["goldBuy_vip"];
			enable(_ui.Btn.goldBtn,boolean);
			//绑定表格
			/*if(_blagFakeFlag==-1)
			{
				_blagFakeFlag= _bind.BindRecord(_model.scene,"FakeVipRec",onaddPerHandle,onremovePerHandle);
			}*/
			if(_ui.Btn.goldBtn.visible == false)
			{
				if(_recordArr.length >0 && _recordArr[1] > 0)
				{
					_canGoldBuy = true;
					_ui.Btn.goldBtn.visible = true;
				} else {
					_canGoldBuy = false;
					_ui.Btn.goldBtn.visible = false;
				}
			}
			refreshDiceBtn();
			sortBtn();
			
		}
		
		/*private function onaddPerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			if(PropertiesValue[0] == DICE_TYPE){
				_recordArr[1] = PropertiesValue[0];
				if(PropertiesValue[1] > 0){
					_ui.Btn.goldBtn.visible = true;
					_canGoldBuy = true;
				} else {
					_ui.Btn.goldBtn.visible = false;
					_canGoldBuy = false;
				}
			}
		}
		
		private function onremovePerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			
		}*/
		
		public function set gold(value:int):void
		{
//			if( value < 10000 )
//			{
//				_ui.goldLab.htmlStr = "元宝："+value.toString();
//			}else
//			{
//				_ui.goldLab.htmlStr = "元宝："+Math.ceil( value / 10000 ) + "万";
//			}
			_ui.goldLab.htmlStr=StaticIni.getSwfLangStr("MagicCoin")+"："+value;
		}
		public function set money(value:int):void
		{
			if( value < 10000 )
			{
				_ui.moneyLab.htmlStr = StaticIni.getSwfLangStr("GoldCoin")+"："+value.toString();
			}else
			{
				_ui.moneyLab.htmlStr = StaticIni.getSwfLangStr("GoldCoin")+"："+int( value / 10000 ) + "万";
			}
		}
		private function clickHandle(e:Event):void
		{
			endDice();
			if(!btnClickHandle(e))
			{
				npcClick(e);
			}
		}
		/**
		 *模拟点击可用的最大npc 
		 * 
		 */		
		private function clickMaxNpc():void
		{
			if(_maxNpcIndex<=0)
				return;
			(ui.pp[NPC+_maxNpcIndex]as EventDispatcher).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		}
		/**
		 *按钮单击 
		 * @param e
		 * @return 
		 * 
		 */		
		private function btnClickHandle(e:Event):Boolean
		{
			var dp:DisplayObject=e.target as DisplayObject;
			if( _ui.Btn["diceBtn"]==(dp) && (dp as SimpleButton).enabled)
			{
				if(_lastLen<MAX_COUNT)
				{
				_beginOneClick=true;
				clickMaxNpc()
//				getCountArrByResult(WIN);
//				beginDice();
				}
				else
				{
					alert();
				}
			}
			else if( _ui.Btn.sellBtn==(dp)	&&_currentAnimalFlag==CURR_NONE)
			{
//				_currentAnimalFlag=CURR_SALE;
				_arrAnimalstuck.push(CURR_SALE)
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_SELL_KUNGFU_AUTO)
			}
			else if(  _ui.Btn.practiceBtn==(dp)	&&_currentAnimalFlag==CURR_NONE)
			{
//				_currentAnimalFlag=CURR_PRAC;
				_arrAnimalstuck.push(CURR_PRAC)
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_PICKUP_KUNGFU_AUTO,int(_ui.seletedMc.currentFrame))
			}
			else if(  _ui.Btn.packBtn==(dp))
			{
				KungfuPackLogic.getInstance().ui.showOrHide();
			}
			else if(  _ui.Btn.exitBtn==(dp))
			{
				close(e);
			}
			else if(_ui.Btn.goldBtn==dp && _ui.Btn.goldBtn.enabled)
			{
				if(_canGoldBuy)
				{
					sendOpenNpc();
					_arrAnimalstuck.push(CURR_BUY);
				}
				else
				{
					alert();
				}
			}
			else if(ui.arrowMain.contains(dp))
			{
				clickMaxNpc();
			}
			else if	(ui.bankBtn.contains(dp))
			{
				if(exchangeMoneyCount>0)
				{
					BanksUI.getInstance().showOrHide();
				}
				else
				{
					NoticeUI.getInstance().showInfo(StaticIni.getSwfLangStr("UIString_1000577"))
				}
			}
			else if	(ui.exchangeBtn.contains(dp))
			{
				ExChangePowerLogic.getInstance().ui.showOrHide();
			}
//			else if(_ui.bk3.contains(dp)/*||_ui.azothLab.contains(dp)*/)
//			{
//				isAzoth=!isAzoth;
//			}
//			else if(_ui.bk2.contains(dp)/*||_ui.normalLab.contains(dp)*/)
//			{
//				isAzoth=!isAzoth;
//			}
			else if(_ui.bk4.contains(dp))
			{
				close(e);
			}
			else if(_ui.seletedMc.contains(dp)||_ui.seletedLab.contains(dp))
			{
				_ui.seletedMc.gotoAndStop(_ui.seletedMc.currentFrame==1?2:1);
			}
			else
			{
				return false
			}
			return true	
		}
		private function set currentNpc(mc:MovieClip):void
		{
			_currentNpc	=	mc;
		}
		/**
		 *npc单击 
		 * @param e
		 * 
		 */		
		private function npcClick(e:Event):void
		{
			var cMc:MovieClip;
			for (var i:int = 0; i < 5; i++) 
			{
				cMc=(_ui.pp[NPC+(i+1)] as MovieClip);
				if(cMc.contains(e.target as DisplayObject))
				{
					
					var count:int=i+1;
					var flag:int=isAzoth?2:1
//					trace("DiceLogic.npcClick(e)当前点击的是第",count,"个npc,",flag,"当前帧数",cMc.currentFrame);
					if(cMc.currentFrame==NPC_NORMAL||cMc.currentFrame==NPC_NOR_ROLL)
					{
						if(_lastLen<MAX_COUNT)
						{
							_arrAnimalstuck.push(CURR_BUY);
							currentNpc=cMc;
							SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_AFFIRM_CHARGE,2,flag,count);
							_ui.arrowMain.visible=false;
							_ui.arrowMain["stop"]();
						}
						else
						{
							alert();
						}
					}
					break;
				}
			}
		}
		/**
		 *重金收买消息 
		 * 
		 */		
		private function sendOpenNpc():void
		{
			var id:int=10
			RequestForCost.getInstance().request(id,sendForCost);
			function sendForCost():void
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_AFFIRM_CHARGE,id);
				LogSendLogic.getInstance().btnClickNumSend(22808);
			}
		}
		/**
		 *背包已经满 
		 * 
		 */		
		private function alert():void
		{
//			AlertUI.showAlert("警告","背包满了");
			NoticeUI.getInstance().showInfo(StaticIni.getSwfLangStr("7047"));
		}
		/**
		 *刷新显示 
		 * 
		 */		
		private function refreshKungfu():void
		{
			var len:int=_ui.constipatGroup.col*_ui.constipatGroup.row;
			for (var i:int = 0; i < len; i++) 
			{
				var mc:MovieClip=_ui.constipatGroup.getItemByIndex(i) as MovieClip;
				if(_constipateArr.length>i)
				{
					mc[DATA]=_tip.getStaticObjWithID(_constipateArr[i]);
				}
				else
				{
					mc[DATA]=null;
				}
				if(!mc[BG])
				{
					//BOOK
					mc[BG]=new NxClip();
					var nx:NxClip=new NxClip();
					nx.source="custSkin_0030";
					mc[IMG].addChild(nx);
					nx.content["face"].addChild(mc[BG]);
					mc[BG2]=nx;
//					(mc[PRAC_BTN] as SimpleButton).addEventListener(MouseEvent.CLICK,linkHandle)
//					mc[SALE_BTN].addEventListener(MouseEvent.CLICK,linkHandle);
					mc.addEventListener(MouseEvent.CLICK,linkHandle);
				}
				mc[INDEX]=i;
				if(mc[DATA])
				{
					mc.visible=true
					var ob:Object=mc[DATA];
//					trace("DiceLogic.refreshKungfu()",ob[MODEL]);
					mc[BG].source=ResPath.PNG+ob[MODEL]+".png"/*String(ob[MODEL]).length<4?"mcpower_"+ob[MODEL]:*/
//					(mc[PRAC_BTN] as SimpleButton).enabled=mc[SALE_BTN].enabled=true;
					btnEnable(mc,true);
					mc[BG2].visible=true;
					((mc[BG2] as NxClip).content as MovieClip).gotoAndStop(ob[BOOK]);
//					trace("DiceLogic.refreshKungfu()",ob[BOOK],mc[BG].source);
//					mc[NAME].htmlText=StaticIni.getSwfLangStr(ob[CONFIGID]);
					switch(int(ob["KungFuQuality"]))
					{
						case KungfuItem.GRAY:
						{
//							mc[INFO].htmlText=saleStr(i);
							mc.gotoAndStop(ONLY_SALE_FRAM)
							break;
						}
						case KungfuItem.RED:
						case KungfuItem.GREEN:
						case KungfuItem.BLUE:
						case KungfuItem.PURPLE:
						case KungfuItem.YELLOW:
						case KungfuItem.EX_YELLOW:
//							mc[INFO].htmlText=practiceStr(i)+"||"+saleStr(i);
//							break;
//							mc[INFO].htmlText=practiceStr(i);
							mc.gotoAndStop(NORMAL_FRAM);
							if(int(ob["KungFuQuality"])==KungfuItem.YELLOW) _model.dispatchEvent(new SoundEvent(SoundEvent.KUNGFU_BEST));
						break;
						default:
						{
							break;
						}
					}
//					trace("DiceLogic.refreshConstipate()",mc[INFO].htmlText);
					
				}
				else
				{
					(mc[BG] as NxClip).clear();
					mc[BG].source="";
					btnEnable(mc,false);
					mc/*[BG2]*/.visible=false;
//					(mc[PRAC_BTN] as SimpleButton).enabled=mc[SALE_BTN].enabled=false;
					
					
//					mc[NAME].htmlText="";
//					mc[INFO].htmlText="";
				}
			}
		}
		/**
		 *刷新按钮 
		 * @param mc
		 * @param enable
		 * 
		 */		
		private function btnEnable(mc:MovieClip,enable:Boolean):void
		{
			if(mc[PRAC_BTN])
			(mc[PRAC_BTN] as SimpleButton).enabled=enable;
			if(mc[SALE_BTN])
			mc[SALE_BTN].enabled=enable;
		}
		/**
		 *npc状态 
		 * @param indeX
		 * @param useAble
		 * 
		 */		
		private function setNpc(indeX:int,useAble:Boolean):void
		{
			if(indeX==4)
			{
				canGoldBuy=useAble?false:(_constipateArr&&_constipateArr.length!=MAX_COUNT)//||!(_constipateArr.length==MAX_COUNT);
				isIndex4	=	useAble;
			}
			if(useAble)
			{
				_ui.pp[NPC+(indeX)].gotoAndStop(NPC_NORMAL);
				_ui.pp[NPC+(indeX)].buttonMode=true
				if(indeX<5)
					_ui.pp[ARROW+indeX].visible=true;
			}
			else
			{
				_ui.pp[NPC+(indeX)].gotoAndStop(NPC_DISBLE);
				_ui.pp[NPC+(indeX)].buttonMode=false;
				if(indeX<5)
					_ui.pp[ARROW+indeX].visible=false;
			}
		}
		private var _endStat:DisplayObject;
		private var _end2Stat:DisplayObject;
		private function close(e:Event):void
		{
			_ui.hide();
			ui.Btn.exitBtn.overState=_endStat;
		}
		public function removeAllEventListener():void
		{
			_ui.windowBG.removeEventListener(MouseEvent.CLICK,clickHandle);
//			_ui.windowBG.removeEventListener(TextEvent.LINK,linkHandle);
			_ui.pp.removeEventListener(MouseEvent.MOUSE_OVER,npcRoll);
			_ui.pp.removeEventListener(MouseEvent.MOUSE_OUT,npcOut);
			_ui.arrowMain.removeEventListener(MouseEvent.ROLL_OVER,arrowTips)
			_ui.arrowMain.removeEventListener(MouseEvent.ROLL_OUT,_tip.hide)
			_ui.constipatGroup.removeItemsEvent(MouseEvent.ROLL_OVER,bookrollOver);
			_ui.constipatGroup.removeItemsEvent(MouseEvent.ROLL_OUT,_tip.hide);
			_ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,close)
			_ui.windowBG.removeEventListener(MouseEvent.DOUBLE_CLICK,npcClick);
			_ui.Btn.removeEventListener(MouseEvent.MOUSE_OVER,btnTips);
			_ui.Btn.removeEventListener(MouseEvent.MOUSE_OUT,_tip.hide);
			if(_blagVipFlag!=-1)
			{
				_blagVipFlag=_bind.UnbindProp(_role,ActorPropertyUI.VIP_LEVLE,_blagVipFlag)
			}
			if(_blagLvlFlag!=-1)
			{
				_blagLvlFlag=_bind.UnbindProp(_role,ActorPropertyUI.LEVEL,_blagLvlFlag)
			}
			if(_blagGoldFlag!=-1)
			{
				_blagGoldFlag=_bind.UnbindProp(_role,"MagicCoin",_blagGoldFlag)
			}
			if(_blagMoneyFlag!=-1)
			{
				_blagMoneyFlag=_bind.UnbindProp(_role,"GoldCoin",_blagMoneyFlag)
			}
			/*if(_blagFakeFlag!=-1)
			{
				_blagFakeFlag= _bind.UnbindRecord("FakeVipRec", _blagFakeFlag);
			}*/
		}
		/**
		 *免费次数 
		 * @param value
		 * 
		 */		
		public function set freeCount(value:int):void
		{
			if(!_totalFreeCount)
				_totalFreeCount=int(StaticIni.getIniVar("BookStoreConfig","PerMaxFreeCount"));
			_ui.normalLab.htmlStrByBorder=StaticIni.getSwfLangStrVar("Kungfu_UIString1",[_totalFreeCount-value]);
		}
		private function beginDice():void
		{
			_result.visible=true;
			_result.htmlStr=StaticIni.getSwfLangStr("UIString_1000630")+_firDiceCountArr.toString()+"  npc的色子是："+_secDiceCountArr.toString();
		}
		private function endDice():void
		{
			_result.visible=false;
		}
		/**
		 * 
		 *根据结果随机骰子数组 
		 * @param result
		 * 
		 */		
		public function getCountArrByResult(result:int):void
		{
			switch(result)
			{
				case WIN:
				{
					_firDiceCountArr=getArrFromZone(4,18);
					_secDiceCountArr=getArrFromZone(3,_firDiceCountArr[3]-1)
					break;
				}
				case TIE:
				{
					_firDiceCountArr=getArrFromZone(3,18);
					_secDiceCountArr=getArrFromZone(_firDiceCountArr[3],_firDiceCountArr[3])
					break;
				}
				case LOSE:
				{
					_secDiceCountArr=getArrFromZone(4,18);
					_firDiceCountArr=getArrFromZone(3,_secDiceCountArr[3]-1)
					break;
				}
				default:
				{
					trace("Error~DiceLogic.getCountArrByResult(result)",result,"不存在");
					break;
				}
			}
			
			
			function getArrFromZone(min:int,max:int):Array
			{
				var total:int=getCountFromZone(min,max);
				var mm:int=total/3
				var count1:int=getCountFromZone(mm,Math.min(6,total-mm-2));
				var count2:int=getCountFromZone(mm,Math.min(6,total-count1-1));
				var count3:int=total-count1-count2;
				return [count1,count2,count3,total];
			}
			function getCountFromZone(min:int,max:int):int
			{
				return int(Math.random()*(max-min+1)+min)
			}
		}
	}
}
